<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>按照Promises/A+规范</title>
</head>

<body>
    <script>
        function Promise1(executor) {
            let that = this
            this.state = 'pending';//状态pending/resolved/rejected
            this.value = undefined;//成功结果
            this.reason = undefined;//失败原因
            this.onFulfilledFunc = [];
            this.onRejectedFunc = [];
            executor(resolve, reject);//传入resolve、 reject两个函数作为参数并执行

            function resolve(value) {
                if (that.state == 'pending') {
                    that.value = value;
                    that.onFulfilledFunc.forEach(fn => {
                        fn(value);
                    })
                    that.state = 'resolved'
                }
            }
            function reject(reason) {
                if (that.state == 'pending') {
                    that.reason = reason;
                    that.onRejectedFunc.forEach(fn => {
                        fn(reason);
                    })
                    that.state = 'rejected';
                }
            }

        }
        Promise1.prototype.then = function (onFulfiled, onRejected) {
            if (this.state == 'pending') {//等待状态，此时异步代码还没走完
                if (typeof onFulfiled == 'function') {
                    this.onFulfilledFunc.push(onFulfiled);//保存回调
                }
                if (typeof onRejected == 'function') {
                    this.onRejectedFunc.push(onRejected);//保存回调
                }
            }
            if (this.state == 'resolved') {
                if (typeof onFulfiled == 'function') {
                    onFulfiled(this.value);
                }
            }
            if (this.state == 'rejected') {
                if (typeof onRejected == 'function') {
                    onRejected(this.reason);
                }
            }
        }

        let p = new Promise1(function aa(resolve, reject) {

            setTimeout(() => {
                console.log('异步代码执行了');

                resolve();
            }, 0)
        })
        p.then(res => {
            console.log('回调1');
        })
    </script>
</body>

</html>